package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.SetmealCheckGroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private SetmealCheckGroupMapper setmealCheckGroupMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional
    @Override
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {

        if (setmeal.getImg() != null){
            redisTemplate.opsForSet().add("set_db", setmeal.getImg());
        }

        setmealMapper.add(setmeal);

        Integer setmealId = setmeal.getId();
        setmealCheckGroupMapper.add(checkgroupIds, setmealId);
    }

    @Transactional
    @Override
    public void edit(Integer[] checkgroupIds, Setmeal setmeal) {

        if (setmeal.getImg() != null){
            Setmeal s = setmealMapper.findById(setmeal.getId());
            redisTemplate.opsForSet().remove("set_db", s.getImg());
            redisTemplate.opsForSet().add("set_db", setmeal.getImg());
        }

        setmealMapper.edit(setmeal);

        Integer  setmealId = setmeal.getId();
        setmealCheckGroupMapper.deleteById(setmealId);
        setmealCheckGroupMapper.add(checkgroupIds, setmealId);
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        return setmeal;
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.selectByCondition(queryPageBean.getQueryString());

        for (Setmeal setmeal : page){
            Integer setmealId = setmeal.getId();
            List<Integer> checkGroupIds = setmealCheckGroupMapper.findCheckGroupIdsBySetmealId(setmealId);
            List<CheckGroup> checkGroups = new ArrayList<>();
            for (Integer checkGroupId : checkGroupIds){
                checkGroups.add(checkGroupMapper.findById(checkGroupId));
            }
            setmeal.setCheckGroups(checkGroups);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }
}
